#!/usr/bin/env ruby
require 'rubygems'
require 'ferret'
require 'fileutils'
require 'rmmseg'
require 'rmmseg/ferret'

include Ferret
include Ferret::Index


def usage(message = nil)
   puts message if message
   puts "ruby #{File.basename(__FILE__)} <index dir> <search phrase>"
   exit(1)
end
 
usage() if ARGV.size != 2
usage("Index '#{ARGV[0]}' doesn't exist.") unless File.directory?(ARGV[0])
$index_dir, $search_phrase = ARGV

RMMSeg::Dictionary.load_dictionaries
RMMSeg::Dictionary.load_words("dict/hidoudou.dic")
RMMSeg::Dictionary.load_words("dict/brands.dic")
RMMSeg::Dictionary.load_words("dict/clothes.dic")
RMMSeg::Dictionary.load_words("dict/star.dic")
  
analyzer = RMMSeg::Ferret::Analyzer.new { |tokenizer|
  Ferret::Analysis::LowerCaseFilter.new(tokenizer)
}
 
index = Index.new(:path => $index_dir, :analyzer => analyzer) 
 
results = []
total_hits = index.search_each($search_phrase) do |doc_id, score| 
  results << "  #{score} - #{index[doc_id][:file_name]}" 
end
 
puts "#{total_hits} matched your query:\n" + results.join("\n")
 
index.close()          
